package ltd.handler;

import java.io.ByteArrayOutputStream;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.CharsetUtil;
import ltd.util.NetUtil;

/**
 * 空闲检测处理    心跳功能
 */
public class IdleHandler extends ChannelInboundHandlerAdapter  {

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		if (evt instanceof IdleStateEvent) {
			IdleStateEvent e = (IdleStateEvent) evt;
			if (e.state() == IdleState.READER_IDLE) {
				System.out.println("--- 心跳超时：服务器 关闭与 该客户端的连接 ---");
				ctx.close();
			} else if (e.state() == IdleState.WRITER_IDLE) {
				//System.out.println("--- 服务器 发送心跳  WRITER ---");
				sendMsg(ctx, "1", 1111);
			} else if (e.state() == IdleState.ALL_IDLE) {
				//System.out.println("--- 服务器 发送心跳  ALL ---");
				sendMsg(ctx, "1", 1111);
			}
		}

	}
	
	public void sendMsg(ChannelHandlerContext ctx, String msgstr, int protocol){
        try {
        	byte[] msgbytes = msgstr.getBytes(CharsetUtil.UTF_8);
			ByteArrayOutputStream bos = new ByteArrayOutputStream(msgbytes.length + 8);

			bos.write(NetUtil.intToByteArray(msgbytes.length + 4));
			bos.write(NetUtil.intToByteArray(protocol));
//        	bos.write(TypeChangeUtil.intToByteArray(0));//备用字段
			bos.write(msgbytes);
			
			ByteBuf resp = Unpooled.copiedBuffer(bos.toByteArray());
			ctx.writeAndFlush(resp);
		} catch (Exception e) {
			System.err.println("### 游戏服务器 客户端 数据发送失败！！！");
			e.printStackTrace();
		}
	}

}
